package com.herench.bs.transfer;

import com.herench.bs.utils.DataFormatUtils;
import com.herench.bs.utils.IdGenerator;
import org.apache.cxf.endpoint.Client;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Date;
import java.util.Map;

/**
 * Created by ThinkPad on 2017/9/1.
 */
public abstract class AbstractTransfer implements Transfer {
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    private final String method;
    private final Client client;
    private final String messageMethod;

    public AbstractTransfer(String method, Client client,String messageMethod) {
        this.method = method;
        this.client = client;
        this.messageMethod = messageMethod;
    }

    public String getMethod() {
        return method;
    }

    public Client getClient() {
        return client;
    }


    public Document getTplDoc(String method) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("BITCRoot");
        root.addElement("CommitData");
        root.addElement("ReturnData");
        Element clientInfo = root.addElement("ClientInfo");
        Element clientInfoElement = clientInfo.addElement("Info");
        clientInfoElement.addAttribute("METHOD", messageMethod).addAttribute("OPT_ID", "1611").addAttribute("OPT_NAME", "微信公众").addAttribute("OPT_IP", "192.168.1.106").addAttribute("OPT_DATE", DataFormatUtils.getTimeString(new Date())).addAttribute("OPT_GUID", IdGenerator.getUUID().toLowerCase()).addAttribute("TOKEN", "").addAttribute("OPT_ACCT", "");
        Element serverInfo = root.addElement("ServerInfo");
        serverInfo.addAttribute("DEV_ID", "").addAttribute("DEV_IP", "").addAttribute("DEV_DATE", "").addAttribute("DEV_GUID", "").addAttribute("DEV_ACCT", "");
        Element resultInfoElement = root.addElement("Result").addElement("Info");
        resultInfoElement.addAttribute("EXECUTE_STATUS", "").addAttribute("EXECUTE_MESSAGE", "");
        return document;
    }


    @Override
    public Map<String, Object> transfer(Map<String, Object> params) throws Exception {
        Map<String, Object> resMap = null;
        String reqMsg = toInvokeMessage(params);
        logger.info("入参：" +reqMsg);
        Object[] array = getClient().invoke(getMethod(), reqMsg);
        String resMsg = (String) array[0];
        logger.info("出参：" +resMsg);
        resMap = toResultMessage(resMsg);
        return resMap;
    }

}
